package org.example.springboot.controller;

//import jakarta.annotation.Resource;
import javax.annotation.Resource;
import org.example.springboot.entity.PageEntity;
import org.example.springboot.entity.User;
import org.example.springboot.service.UserService;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

//@WebServlet("/users")
@CrossOrigin //解决跨域问题
@RestController //定义控制器
@RequestMapping("/users") //定义url
public class UserController extends BaseServlet {

    //调用业务层
    @Resource
    private UserService userService;

    @RequestMapping("/login")
    public ResponseEntity<User> login(String username, String password){

        User user = userService.login(username, password);
        //将登录验证结果发送前端
        return ResponseEntity.ok(user);
    }


    @RequestMapping("/page")
    public ResponseEntity<PageEntity<User>> page(Integer current, Integer pageSize) {
        //查询用户
        PageEntity<User> users = userService.findUserPage(current,pageSize);
        //转换为JSON,通过流发送给客户端
        return ResponseEntity.ok(users);
    }

    //将方法名称作为参数传递  m=save
    @RequestMapping("/save")
    public ResponseEntity<Boolean> save(HttpServletRequest req) {
        String userId = req.getParameter("user_id");
        String userName = req.getParameter("user_name");
        String userPwd = req.getParameter("user_pwd");
        String userType = req.getParameter("user_type");
        User user = new User(userId,userName,"123456",Integer.valueOf(userType));
        //查询用户
        boolean rs = userService.save(user);
        return ResponseEntity.ok(rs);
    }

    @RequestMapping("/update")
    public ResponseEntity<Boolean> update(HttpServletRequest req) throws IOException {
        String userId = req.getParameter("user_id");
        String userName = req.getParameter("user_name");
        String userPwd = req.getParameter("user_pwd");
        String userType = req.getParameter("user_type");
        User user = new User(userId,userName,userPwd,Integer.valueOf(userType));
        //查询用户
        boolean rs = userService.update(user);
        return ResponseEntity.ok(rs);
    }

    @RequestMapping("/delete")
    public ResponseEntity<Boolean> delete(HttpServletRequest req) {
        String userId = req.getParameter("user_id");
        //查询用户
        boolean rs = userService.remove(userId);
        return ResponseEntity.ok(rs);
    }
}
